var selectedMenuName;  
var queryType = false  // 是否进行查找 
var resetType = false  // 是否进行重置
var quueryData = [] // 查找的到的数据
var editMetaData = [] // 编辑元数据  
var LAYERALIASNameType = true // 判断编辑元数据名称图层名称是否重复 
if (sessionStorage.getItem('dataResource_curr') != null) {
    sessionStorage.setItem('dataResource_curr',1)
}
function initTopEvent() {
    $('#registResourceBtn').click(function () {
        layer.open({
            type: 2,
            title: '注册数据资源',
            shadeClose: true,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            area: ['900px', '600px'],
            content: '/BasePlatform/DataServer/services.html', //iframe的url
            end:function () {
                let serverType = sessionStorage.getItem('serviceTypeName')
                if (serverType == 'true') {
                    layer.msg('注册成功', {icon: 1,time: 1000,shade : [0.5 , '#000' , true]});
                    sessionStorage.removeItem('serviceTypeName')
                }
            }
        });
    })
}
//初始化左侧资源列表树
function initTree() {
    var listData = getListData();
    var DTree = dtree.render({
        elem: "#ResourceCatalogTree",
        data: listData,
        width: "300",
        ficon: ["1", "-1"], //隐藏最后一级的小黑点
        checkbar: true,
        checkbarType: "no-all", //半选 默认就是all，其他的值为： no-all  p-casc   self  only
        accordion: true,
        menubar: false,
        done: function (data, obj) {
            $("#search_btn").unbind("click");
            $("#search_btn").click(function () {
                var value = $("#searchInput").val();
                if (value) {
                    var flag = DTree.searchNode(value); // 内置方法查找节点
                    if (!flag) {
                        layer.msg("该名称节点不存在！", {
                            icon: 5
                        });
                    }
                } else {
                    DTree.menubarMethod().refreshTree(); // 内置方法刷新树
                }
                bindingTreeEvent();
            });
        }
    });
    // 点击节点触发回调
    dtree.on("node('ResourceCatalogTree')", function (obj) {
        if (!obj.param.leaf) {
            var $div = obj.dom;
            DTree.clickSpread($div); //调用内置函数展开节点
        }
        TreeID = obj.param.nodeId;
        getMyDataByNodeID(TreeID);
    });
}
//对左侧目录数据进行处理
function getListData() {
    var data = getTreeData();
    var pid = "";

    function mapTree(data) {
        if (data["$ref"]) {
            return;
        }
        const haveChildren = Array.isArray(data.children) && data.children.length > 0;
        if (isNull(data.PID)) {
            pid = "0"
        } else {
            pid = data.PID
        }
        var title = data.NAME.length > 12 ? data.NAME.substr(0, 11) + "..." : data.NAME;
        var obj = {
            id: data.GUID ? data.GUID : data.TREEID,
            parentId: pid,
            title: data.COUNT > 0 ? title + "[" + data.COUNT + "]" : title,
            //title:title,
            children: haveChildren ? data.children.map(i => mapTree(i)) : [],
        };
        if (data.ADDRESS) {
            obj["checkArr"] = [{
                "type": "0",
                "checked": "0"
            }];
            if (data.ZYLX == '4') {
                obj.id = data.RESOURCEID;
                obj["ficonClass"] = "dtree-icon-shijian";
                obj["iconClass"] = "dtree-icon-normal-file";
            } else {
                obj["ficonClass"] = "dtree-icon-shijian";
                obj["iconClass"] = "dtree-icon-xinxipilu";
            }
        } else if (!data.children) {
            obj["ficonClass"] = "dtree-icon-weibiaoti5";
            obj["iconClass"] = "dtree-icon-weibiaoti5";
        }
        return obj;
    };
    let res = []
    res = data.map(function (currentValue, index, arr) {
        if (typeof (currentValue) == "string") {

        } else {
            return mapTree(currentValue);
        }
    });
    return res;
}
//获取左侧目录
function getTreeData() {
    var thisResult = null;
    $.ajax({
        type: "post",
        async: false,
        url: modelURL + "dataAccount/getDataAccountTrees",
        data: //发送到服务器的参数
        {
            orgId: portaluserdept,
            userNo: portaluserno,
        },
        datatype: "json",
        success: function (result) {
            let data = JSON.parse(result)
            thisResult = data.data;
        },
        error: function (err) {
            if (err.status == 405)
                top.location.href = '/';
        }
    });
    return thisResult;
}
//初始化右侧表格数据
function initTable(data) {
    colType = $("#serverType").val()
    ipt_collect_name = $('#ipt_search').val();
    table.render({
        elem: '#DataTable',
        id: 'DataTable',
        data: data,
        page: {
            limit: 20,
            curr: sessionStorage.getItem('dataResource_curr') ? sessionStorage.getItem('dataResource_curr') : 1
        },
        toolbar: true,
        toolbar: '#tbDataToolBar' //这里在左边显示，然后指定到模版id
            ,
        cols: [
            [{
                type: 'numbers',
                title: '序号',
                align: 'center',
                width: 100
            }, {
                field: 'NAME',
                title: '数据资源名称',
                align: 'center'
            }, {
                field: 'ZYLX',
                title: '资源类型',
                align: 'center'
            }, {
                field: 'SAVEDATE',
                title: '注册时间',
                align: 'center'
            }, {
                field: 'SERVICE_STATUS',
                title: '服务状态',
                align: 'center',
                templet: '#operationManDiv'
            }, {
                align: 'center',
                title: '资源操作',
                toolbar: '#data-table-operate'
            }]
        ],
        response: {
            statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.status, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.total, //解析数据长度
                "data": res.rows.item //解析数据列表
            };
        },
        done: function (res, curr, count) { 
            sessionStorage.setItem('dataResource_curr', curr)
            $("[data-field = 'ZYLX']").children().each(function () {
                for (var key in serverTypes) {
                    var oneData = serverTypes[key];
                    if ($(this).text() == "" + oneData.ZDVALUE + "") {
                        $(this).text(oneData.ZDTITLE);
                    }
                }
            });
            TableData = layui.table.cache["DataTable"];
        }
    });
    initDropdown();
    $("#serverType").val(colType);
    $('#ipt_search').val(ipt_collect_name);
    layui.form.render('select');
}

function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}
//根据左侧树id获取数据
function getMyDataByNodeID(id, resourceType, resourceName) {
    var data = {};
    var url = null;
    if (!isNull(id)) {
        data = {
            id: id,
            orgId: portaluserdept,
            userNo: portaluserno
        }
        url = modelURL + "dataAccount/getResourcesById";
    } else if (!isNull(resourceType) || !isNull(resourceName)) {
        data = {
            startTime: "",
            endTime: "",
            name: resourceName,
            position: "",
            company: "",
            zylx: isNull(resourceType) ? "" : "('" + resourceType + "')",
            orgId: portaluserdept,
            userNo: portaluserno
        }
        url = modelURL + "dataAccount/getDataAccountByIs";
    } else {
        data = {
            key: "",
            orgId: portaluserdept,
            userNo: portaluserno
        }
        url = modelURL + "dataAccount/getDataAccountByLike";
    }
    var resultData = null;
    var results = null;
    results = sendAjax(url, "POST", data);
    if (results.code == 200) {
        resultData = results.data;  
        resultData.sort(creatCompare("SAVEDATE"))
        resultData.map(function (item, index) {
            return item.SAVEDATE = formatDate(item.SAVEDATE);
        })
        if (!resourceName == '') {
            queryType = true 
            quueryData = results.data  
            sessionStorage.setItem('dataResource_curr',1) 
            initTable(quueryData);
        } else if (id == '' && resourceType == '' && resourceName == '' && resetType || id == undefined && resourceType == undefined && resourceName == undefined && resetType) {
            queryType = false  
            resetType = false 
            sessionStorage.setItem('dataResource_curr',1) 
            initTable(resultData); 
        } else {
            queryType = false  
            initTable(resultData); 
        }
    } else {
        layer.msg("数据获取失败！", {
            icon: 5
        });
    }
    return resultData;
}
//根据guid获取元数据
function getLayerInfoByGUID(resourcesID) {
    var thisResult = null;
    var results = null;
    results = sendAjax(modelURL + "resource/getResourceByGuid", "POST", {
        guid: resourcesID
    });
    if (results.code == 200) {
        if (results != "null") {
            thisResult = results.data;
        }
    } else {
        layer.msg("获取元数据失败！", {
            icon: 5
        });
    }
    return thisResult;
}
//服务状态修改
function updateServerStatus(id, status) {
    var results = null;
    results = sendAjax(modelURL + "resource/upTbResourceStatus", "POST", {
        resourceid: id,
        serviceStatus: status
    });
    if (results.code == 200) {
        layer.msg("服务状态修改成功！", {
            icon: 1
        });
    } else {
        layer.msg("服务状态修改失败！", {
            icon: 5
        });
    }
    return results;
}
//模糊查询
function searchDate() {
    var resourceType = $('#serverType').val();
    var resourceName = $('#ipt_search').val();
    getMyDataByNodeID("", resourceType, resourceName)
}
//编辑元数据
function edtMetaData(obj) {
    if (!onceRequestTAG) {
        fillLayerDropdown('ipt_form_select');
    }
    if (obj.data.ZYLX == "3") {
        var resourcesID = obj.data.RESOURCEID;
        editMetaData = getLayerInfoByGUID(resourcesID);
        var layerInfo = getLayerInfoByGUID(resourcesID);
        for (var key in layerInfo) {
            layerInfo = layerInfo[key];
            break;
        }
        var isqueryVal;
        if (layerInfo.ISQUERY == "是" || layerInfo.ISQUERY == "1") {
            isqueryVal = "1";
        } else {
            isqueryVal = "0";
        }
        //地图服务数据表单回显
        form.val('MapServiceBasicdataForm', {
            "LAYERALIAS": layerInfo.LAYERALIAS,
            "COMPANY": layerInfo.COMPANY,
            "SPATIAL": layerInfo.SPATIAL,
            "SERVICESTYPE": layerInfo.SERVICE_CATEGORY,
            "RESOURCEPOSITION": layerInfo.POSITION,
            "ADDRESS": layerInfo.ADDRESS,
            // "ID": layerInfo.ID,
            "STYLE": layerInfo.STYLE,
            "POSITION": layerInfo.LAYERPOSITION,
            "PRJ": layerInfo.PRJ,
            "PARAMETERS": layerInfo.PARAMETERS,
            "SERVICETYPE": layerInfo.SERVICETYPE,
            "SOURCE": layerInfo.SOURCE,
            "STATUS": layerInfo.STATUS,
            "ISQUERY": isqueryVal,
            "SERVERTYPE": layerInfo.SERVERTYPE,
            "YEAR": layerInfo.YEAR,
            "ZYTB": layerInfo.ZYTB
        });
        var metadata = JSON.parse(layerInfo.META_DATA);
        form.val('MapServiceMetadataForm', {
            "SERVICEVERSION": metadata.SERVICEVERSION,
            "GEODETICDATUMCOORDINATE": metadata.GEODETICDATUMCOORDINATE,
            "HEIGHTDATUM": metadata.HEIGHTDATUM,
            "CENTRALMERIDIAN": metadata.CENTRALMERIDIAN,
            "WESTLON": metadata.WESTLON,
            "NORTHLAT": metadata.NORTHLAT,
            "EASTLON": metadata.EASTLON,
            "SOUTHLAT": metadata.SOUTHLAT,
            "DATARELEASEUNIT": metadata.DATARELEASEUNIT,
            "SERVICERELEASETIME": metadata.SERVICERELEASETIME,
            "CONTACTPHONENUMBER": metadata.CONTACTPHONENUMBER,
            "HEADOFUNIT": metadata.HEADOFUNIT
        });
        layer.open({
            type: 1,
            title: "查看元数据",
            shadeClose: true, //点击遮罩关闭
            area: ["500px", "700px"],
            content: $("#MapServiceMetadataLayer"),
            btn: ['修改', '取消'],
            yes: function (index, layero) {
                UpdataMapServerData(index, resourcesID)
            },
            btn2: function (index, layero) {
                layer.close(index);
            }
        });
    } else {
        layer.msg("目前只能编辑地图服务。。。")
    }
}

function UpdataMapServerData(index, resourceId) {
    var data = form.val('MapServiceBasicdataForm');
    data["LAYERNAME"] = pinyin.getCamelChars(data.LAYERALIAS);
    // 验证必填项是否为空
    var isNotNull = mapSercerVerify(data);
    if (isNotNull) {
        if (LAYERALIASNameType) {
            var metaDataFormInfo = form.val('MapServiceMetadataForm');
            var metaDataInfos;
            metaDataInfos = {
                "SERVICEVERSION": metaDataFormInfo.SERVICEVERSION,
                "GEODETICDATUMCOORDINATE": metaDataFormInfo.GEODETICDATUMCOORDINATE,
                "HEIGHTDATUM": metaDataFormInfo.HEIGHTDATUM,
                "CENTRALMERIDIAN": metaDataFormInfo.CENTRALMERIDIAN,
                "WESTLON": metaDataFormInfo.WESTLON,
                "NORTHLAT": metaDataFormInfo.NORTHLAT,
                "EASTLON": metaDataFormInfo.EASTLON,
                "SOUTHLAT": metaDataFormInfo.SOUTHLAT,
                "DATARELEASEUNIT": metaDataFormInfo.DATARELEASEUNIT,
                "SERVICERELEASETIME": metaDataFormInfo.SERVICERELEASETIME,
                "CONTACTPHONENUMBER": metaDataFormInfo.CONTACTPHONENUMBER,
                "HEADOFUNIT": metaDataFormInfo.HEADOFUNIT
            };
            metaDataInfos = JSON.stringify(metaDataInfos);
            $.ajax({
                type: "post",
                async: false,
                url: modelURL + "resource/updateLayerInfo",
                data: //发送到服务器的参数
                {
                    guid: resourceId,
                    layername: data.LAYERNAME, //图层名
                    layeralias: data.LAYERALIAS, //图层名称别名
                    name: data.LAYERALIAS, //图层名称别名
                    company: data.COMPANY, //所属单位
                    spatial: data.SPATIAL, //主题
                    // id: data.ID, //服务ID
                    style: data.STYLE, //样式
                    layerposition: data.POSITION, //定位信息
                    prj: data.PRJ, //投影信息
                    parameters: data.PARAMETERS, //服务图层名
                    servertype: data.SERVERTYPE, //地图服务类型
                    source: data.SOURCE, //图层源类型
                    status: data.STATUS, //加载状态
                    isquery: data.ISQUERY, //是否可查
                    servicetype: data.SERVICETYPE, //地图服务类型
                    year: data.YEAR, //数据年份
                    zytb: data.ZYTB, //资源图标
                    position: data.RESOURCEPOSITION, //提供方
                    address: data.ADDRESS, //服务地址
                    userno: portaluserno,
                    serviceCategory: data.SERVICESTYPE, //服务种类
                    metaData: typeof (metaDataInfos) == 'string' ? metaDataInfos : JSON.stringify(metaDataInfos)
                },
                datatype: "json",
                success: function (result) {
                    let data1 = JSON.parse(result) 
                    var thisResult = data1.data;
                    if (thisResult == "error") {
                        layui.layer.msg('操作有误!', {
                            icon: 5
                        })
                        return;
                    }
                    if (thisResult == "True") { 
                        layui.layer.msg('修改成功', {
                            icon: 1
                        }); 
                        if ($('#ipt_search').val() == '') {
                            getMyDataByNodeID();
                        } else if (queryType){
                            // sessionStorage.setItem('MyData_curr',1)  
                            var resourceType = $('#serverType').val();
                            var resourceName = $('#ipt_search').val();
                            getMyDataByNodeID("", resourceType, resourceName) 
                        }
                        layer.close(index);
                    } else if (thisResult == "False") {
                        layui.layer.msg('修改失败!', {
                            icon: 5
                        })
                    }
                },
                error: function (err) {
                    if (err.status == 405)
                        top.location.href = '/';
                }
            });
        } else {
            layui.layer.msg('应用名称重复,请重新输入', {
                time: 1000,
                icon: 5,
                shift: 6
            })
        }
    }
}

//发布服务
function publishServer() {
    layer.open({
        type: 2,
        title: '发布服务',
        shadeClose: true,
        shade: false,
        maxmin: true, //开启最大化最小化按钮
        area: ['900px', '600px'],
        content: '/BasePlatform/DataServer/MapServerPublish.html'
    });
}
//权限管理
function permissionManage(obj) {
    layer.open({
        type: 2,
        title: "权限管理",
        shadeClose: true, //点击遮罩关闭
        area: ["800px", "600px"],
        // content: $("#permissionManagerLayer"),
        maxmin: true, //开启最大化最小化按钮
        content: '/BasePlatform/Permission/permissionManage.html',
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            var iframe = window['layui-layer-iframe' + index];
            iframe.updatePermission();
        },
        btn2: function (index, layero) {
            layer.close(index);
        },
        success: function (layero, index) {
            var iframe = window['layui-layer-iframe' + index];
            var param = {
                resourceId: obj.data.RESOURCEID,
                zylx: obj.data.ZYLX
            }
            iframe.getParentParams(param);
        }
    });
}
//删除
function deleteData(obj) {
    var results = null;
    layer.confirm("确认要删除吗？", {
            title: "删除"
        },
        function (index) {
            if (index) {
                results = sendAjax(modelURL + "data/deleteDataById", "POST", {
                    id: obj.data.RESOURCEID
                });
                if (results.code == 200) {
                    layer.msg("删除成功！", {
                        icon: 1
                    });
                    getMyDataByNodeID();
                    $("#serverType").val("");
                    $('#ipt_search').val("");
                    form.render('select');
                } else {
                    layer.msg("删除失败！", {
                        icon: 5
                    });
                }
                layer.close(index);
            }
        })
}

//验证地图服务查看元数据弹框的必填项
function mapSercerVerify(data) {
    if (!data.LAYERNAME) {
        layer.msg("请填写图层名称！", {
            icon: 5
        });
        return false;
    } else if (!data.ADDRESS) {
        layer.msg("请填写服务地址！", {
            icon: 5
        });
        return false;
    } else if (!data.POSITION) {
        layer.msg("请填写定位信息！", {
            icon: 5
        });
        return false;
    } else if (!data.PRJ) {
        layer.msg("请填写投影信息！", {
            icon: 5
        });
        return false;
    } else if (!data.PARAMETERS) {
        layer.msg("请填写服务图层名！", {
            icon: 5
        });
        return false;
    } else if (!data.PARAMETERS) {
        layer.msg("请填写服务图层名！", {
            icon: 5
        });
        return false;
    } else {
        return true;
    }
}
//获取下拉列表
function initDropdown() {
    for (var i = 0; i < serverTypes.length; i++) {
        $("[name='serverType']").append("<option value='" + serverTypes[i].ZDVALUE + "'>" + serverTypes[i].ZDTITLE + "</option>");
    }
    layui.form.on('select(serverTypeSelect)', function (data) {
        $("#serverType").val(data.value);
        colType = $("#serverType").val()
    });
}
//填充图层字段下拉框
function fillLayerDropdown(className) {
    var layerSelects = $("." + className);
    var oneSelect, oneSelectName, zdName, dataDict;
    for (var i = 0; i < layerSelects.length; i++) {
        oneSelect = layerSelects[i];
        oneSelectName = oneSelect.attributes.name.value;
        if (oneSelectName == "SPATIAL") {
            zdName = "spatial";
            dataDict = getDataDict(zdName);
        } else if (oneSelectName == "SERVICESTYPE") {
            dataDict = getDataDict("serviceType");
        } else {
            zdName = "layer" + oneSelectName.toLowerCase();
            dataDict = getDataDict(zdName);
        }
        var oneDataDict;
        $(oneSelect).empty();
        for (var key in dataDict) {
            oneDataDict = dataDict[key];
            $(oneSelect).append("<option value='" + oneDataDict.ZDVALUE + "' title='" + oneDataDict.ZDTITLE + "'>" + oneDataDict.ZDTITLE + "</option>");
        }
        if (oneSelectName == "RESOURCEPOSITION") {
            var strPositionData = null;
            strPositionData = getSpecialDataDict("position");
            $(oneSelect).empty();
            for (var key in strPositionData) {
                oneDataDict = strPositionData[key];
                $(oneSelect).append("<option ip = '" + oneDataDict.ZDVALUE + "'  value='" + oneDataDict.ID + "' title='" + oneDataDict.ZDTITLE + "'>" + oneDataDict.ZDTITLE + "</option>");
            }
        }
        if (oneSelectName == "COMPANY") {
            var strCompanyData = null;
            strCompanyData = getCompanyDataDict(portaluserno);
            $(oneSelect).empty();
            $(oneSelect).append("<option value='" + strCompanyData.FK_DEPT + "' title='" + strCompanyData.FK_DEPTTEXT + "'>" + strCompanyData.FK_DEPTTEXT + "</option>");
        }
    }
    layui.form.render('select');
    onceRequestTAG = true;
}
//资源图标预览
function viewIcon(className) {
    var iconFileSelectNode = $("input[class*='" + className + "'][name='ZYTB']");
    if (iconFileSelectNode.val() == "" || iconFileSelectNode.val() == null || iconFileSelectNode.val() == "undefined") {

    } else {
        iconFileName = iconFileSelectNode.val();
        open("/img/BasePlatform/resource/" + iconFileName);
    }
}